<template>
  <van-nav-bar
    title="狗东登录"
    left-text="返回"
    left-arrow
    @click-left="$router.back()"
  />
  <!-- 表单区域 -->
  <van-form @submit="onSubmit">
    <van-cell-group inset>
      <van-field
        v-model="loginname"
        name="用户名"
        label="用户名"
        placeholder="用户名"
        :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
        v-model="password"
        type="password"
        name="password"
        label="密码"
        placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
    </van-cell-group>
    <div style="margin: 16px">
      <van-button round block type="primary" native-type="submit">
        提交
      </van-button>
    </div>
  </van-form>
  <!-- 注册区域 -->
  <van-cell-group title="去注册">
    <van-cell title="快速注册" is-link to="/regist" />
  </van-cell-group>
</template>

<script setup lang="ts">
import { ref } from "vue";
import type { Ref } from "vue";
import { userLogin } from "@/api/api";
import { useUsrInfoStore } from "@/stores/userinfo";
import { useRouter } from "vue-router"
import { showSuccessToast, showFailToast } from 'vant';

interface IuserForm {
  loginname: string;
  password: string;
}
interface IuserLoginApi {
  code: "200" | "10001" | "10010";
  data: {
    token: string;
    userid: string;
  };
  message: string;
}

const loginname: Ref<string> = ref("");
const password: Ref<string> = ref("");
const store = useUsrInfoStore();
const router = useRouter();

const onSubmit = async (values: IuserForm) => {
  console.log("submit", values);
  const res = await userLogin(values);
  console.log(res);
  if ((res as unknown as IuserLoginApi).code === "200") {
    const token = res.data.token;
    store.setUserToken(token);
    localStorage.setItem("userToken", token);
    showSuccessToast((res as unknown as IuserLoginApi).message)
    router.push("/")
  }else{
    showFailToast((res as unknown as IuserLoginApi).message)

  }
};
</script>
<style>
</style>
